package com.beiding.dao;

import com.beiding.config.Config;
import com.beiding.timeout.dao.TaskIndexMap;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;

@Repository
public class TaskIndexMapImpl implements TaskIndexMap {

    private List<String> empty = Collections.emptyList();

    private ListOperations<String, String> listOperations;

    RedisTemplate<String, String> redisTemplate;

    public TaskIndexMapImpl(RedisConnectionFactory factory, StringRedisSerializer stringRedisSerializer, Config.LongRedisSerializer longRedisSerializer) {

        redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(factory);

        redisTemplate.setKeySerializer(stringRedisSerializer);

        redisTemplate.afterPropertiesSet();

        listOperations = redisTemplate.opsForList();

    }

    @Override
    public List<String> getListByTime(long time) {//获取对应时间点的任务id列表

        String key = "test:taskIndex:lists:" + time;
        Long size = listOperations.size(key);

        if (size > 0) {
            return listOperations.range(key, 0, size);
        }

        return empty;
    }

    //在对应的时间点添加一个事假
    @Override
    public void putTask(long time, String id) {
        listOperations.leftPush("test:taskIndex:lists:" + time, id);
    }

    @Override
    public void remove(long time) {
        redisTemplate.delete("test:taskIndex:lists:" + time);
    }
}
